/**
 * 边界高亮图层
 */
import sgisRegionBase from "../../sfgis.region.base.js";
import regionLableLayer from "../../lib/systemlayers/region.marker.layer";
import sgisSpatialQuery from "../../sfgis.spatial.query.js";
import regionLable from "./region.marker.layer";
import historyHlLayer from "./history.hl.layer";
export default {
  HLLayer: null, // 高亮图层组
  activeMap:null,
  //高亮图层source
  hlSource:{
    "type": "geojson",
    "data": {
      "type": "Feature",
      "geometry": {
        "type": "Polygon",
        "coordinates": [[]]
      }
    }
  },
  //layerType,type为fill时提供双击下钻，为line不提供双击下钻
  initHLLayer(map,layerType) {
    if(map.getLayer("hl-layer-map") !== null && map.getLayer("hl-layer-map") !== undefined){
      map.removeLayer("hl-layer-map");
    }
    if(map.getLayer("hl-layer-map-line") !== undefined){
      map.removeLayer("hl-layer-map-line");
    }
    if(map.getSource("hl-source-map") !== null && map.getSource("hl-source-map") !== undefined){
      map.removeSource("hl-source-map");
    }
    if(layerType === "fill"){
      this.HLLayer = {
        "id": "hl-layer-map",
        "type": "fill",
        "source": "hl-source-map",
        "paint": {
          "fill-color": "rgba(105, 151, 234,0.15)",
          'fill-outline-color': "red",
        }
      };
    }else if(layerType === "line") {
      this.HLLayer = {
        "id": "hl-layer-map",
        "type": "line",
        "source": "hl-source-map",
        "paint": {
          // "line-color": "hsl(351,69%,40%)",
          "line-color": "rgb(105, 151, 234)",
          "line-width": {
            "base": 1.55,
            "stops": [
              [13,1.8],
              [20,20]
            ]
          },
          "line-opacity": 0.9
        },
      };
    }
    map.addSource("hl-source-map",this.hlSource);
    map.addLayer(this.HLLayer);
    if(layerType === "fill"){
      // map.on("dblclick","hl-layer-map",function(e) {
      //   let QH_CODE = e.features[0].properties.QH_CODE;
      //   let QH_NAME = e.features[0].properties.QH_NAME;
      //   console.log("当前点击选中区划###" + QH_NAME + "####" + QH_CODE);
      // });
    }
    this.activeMap = map;
  },
  // 为指定区划添加区划边界（包含两级，当前传过来的指定区划和）
  /**
   * 根据区划添加边界
   * regionInfos 区划信息
   * type 区划类型   type=1  普通区划 3 特色区 2高新区
   * haschild 是否有下级
   * hasMaskBoundary 是否添加蒙版（true/false） 可为空
   */
  addHLBoundary(regionInfos, type, map, haschild,hasMaskBoundary) {
    let _this = this;
    sgisSpatialQuery.spatialQueryUtil.getFeaturesByRegionCodes(
      regionInfos,
      type,
      function(serviceResult) {
        // 设置一下
        if (serviceResult.type=="processCompleted" && serviceResult.result.features && serviceResult.result.features !== null &&serviceResult.result.features.features.length!=0) {
          // if (haschild) { // 如果包含下级区划，添加下层区划边界 color 灰色 宽度 1 (此处适合普通区划，特色区划规则不符合)
            // 添加蒙版图层
            if (hasMaskBoundary !== undefined && hasMaskBoundary){
              _this.addMaskBoundary(serviceResult.result.features, map);
            }
            // 保存一下区划面
            sgisRegionBase.regionInfos.setCurrentRegionBounds(serviceResult.result.features);

            // 添加父级区划图层
            _this.refreshBoundaryFeatures(serviceResult.result.features,map,"line");
            // 保存一下区划
            sgisRegionBase.regionInfos.setCurrentRegionInfos(regionInfos);
            // 添加区划标签
            _this.addRegionLableByRegionInfos(regionInfos,map);
            let childRegionInfos = [];
            if (regionInfos && regionInfos !== null && regionInfos.length > 0) {
              for (let i = 0; i < regionInfos.length; i++) {
                let temp = JSON.parse(JSON.stringify(regionInfos[i]));
                temp.regioncode = sgisRegionBase.regionUtils.caluMacRegion(
                  parseInt(temp.regionlevel) + 1 + "",
                  temp.regioncode
                ); // 此处区划等级+1，获取下级行政区划的边界
                childRegionInfos.push(temp);
              }
              sgisSpatialQuery.spatialQueryUtil.getFeaturesByRegionCodes(
                childRegionInfos,
                type,
                function(serviceResult) {
                  if (!serviceResult) return;
                  // 添加本层区划边界 color 红色 宽度 3 CLayers
                  if(map.getSource("c-hl-source-map") == null || map.getSource("c-hl-source-map") === null){
                    let  cHlSource = {
                      "type": "geojson",
                      "data": {
                        "type": "Feature",
                        "geometry": {
                          "type": "Polygon",
                          "coordinates": [[]]
                        }
                      }
                    };
                    map.addSource("c-hl-source-map",cHlSource);
                  }else {
                    //清除原有数据
                    map.getSource('c-hl-source-map').setData({
                      "type": "Feature",
                      "geometry": {
                        "type": "Polygon",
                        "coordinates": [[]]
                      }
                    });
                  }
                  //添加子区划所用图层，图层顺序在父图层之前
                  if(map.getLayer("c-hl-layer-map") === null || map.getLayer("c-hl-layer-map") === undefined){
                    map.addLayer({
                      "id": "c-hl-layer-map",
                      // "type": "fill",
                      "type":"line",
                      "source": "c-hl-source-map",
                      "paint": {
                        // "fill-color": "rgba(0, 0, 255, 0.03)",
                        // 'fill-outline-color': "#4f5050",

                        "line-color": "rgba(145,144,141 ,0.81)",
                        "line-width": 1,
                      },
                    },"hl-layer-map");
                  }
                  map.getSource('c-hl-source-map').setData(serviceResult.result.features);
                  //双击下钻区划(只有layer的type为fill时候采用dbclick，为line的时候不用)
                  // map.on("dblclick","c-hl-layer-map",function(e) {
                  //   if(e.features && e.features.length >0){
                  //     let QH_CODE = e.features[0].properties.QH_CODE;
                  //     let QH_NAME = e.features[0].properties.QH_NAME;
                  //     console.log("当前点击选中区划###" + QH_NAME + "####" + QH_CODE);
                  //   }
                  // });
                }
              );
            }
          // }else{//没有下级
          //   // 添加蒙版图层
          //   if(hasMaskBoundary !== undefined && hasMaskBoundary){
          //     _this.addMaskBoundary(serviceResult.result.features, map);
          //   }
          //   //添加父级区划高亮图层
          //   _this.refreshBoundaryFeatures(serviceResult.result.features,map,"fill");
          //   // 保存一下区划
          //   sgisRegionBase.regionInfos.setCurrentRegionInfos(regionInfos);
          //   //添加区划标签
          //   _this.addRegionLableByRegionInfos(regionInfos,map);
          // }
        }
      }
    );

    // 添加历史区划边界数据
    historyHlLayer.addHIsHLBoundarys(regionInfos,type,map);
  },
  addMtPoly(blist){
    let mtPoly = {
      "type": "Feature",
      "properties": {},
      "geometry": {
        "type": "MultiPolygon",
        "coordinates":
          [
            [
              [
                [-180,90],
                [180,92],
                [180,-90],
                [-180,-90],
                [-180,90]
              ],
            ]
          ]
      }
    };
    let features = blist.features;
    for (var i = 0; i < features.length; i++){
      let feature = features[i];
      for(var j = 0 ; j < feature.geometry.coordinates.length ; j++){
        let coordinate = feature.geometry.coordinates[j];
        for(var k = 0 ; k < coordinate.length; k++){
           mtPoly.geometry.coordinates[0].push(coordinate[k]);
        }
      }
    }
    return mtPoly;
  },
  // 增加添加高亮图层方法
  addMaskBoundary(blist,map) {
    let mtPoly = this.addMtPoly(blist);
    map.addLayer({
      "id": "QueryBondsArea",
      "type": "fill",
      "source": {
        "type": "geojson",
        "data": mtPoly
      },
      "paint": {
        // 半透明深蓝色蒙版
        // "fill-color": "rgba(201, 201, 201,0.90)",
        "fill-outline-color": "rgba(172, 220, 243,0)",

        // 不透明白色蒙版
        "fill-color": "rgba(30,84,111,0.9)",
        // "fill-outline-color": "#ffffff"**/
      }
    }," overlayer-tag");
  },
  // addMaskBoundary(blist,map) {
  //   blist = blist.features;
  //   /* 画遮蔽层的相关方法
  //    * 思路: 首先在中国地图最外画一圈，圈住理论上所有的中国领土，然后再将每个闭合区域合并进来，并全部连到西北角。
  //    *      这样就做出了一个经过多次西北角的闭合多边形*/
  //   // 定义中国东南西北端点，作为第一层
  //   const pNW = [-180,90];
  //   const pNE = [180,90];
  //   const pSE = [180,-90];
  //   const pSW = [-180,-90];
  //   // 向数组中添加一次闭合多边形，并将西北角再加一次作为之后画闭合区域的起点
  //   let pArray = [];
  //   pArray.push(pNW);
  //   pArray.push(pSW);
  //   pArray.push(pSE);
  //   pArray.push(pNE);
  //   pArray.push(pNW);
  //   // 循环添加各闭合区域
  //   for (let i = 0; i < blist.length; i++) {
  //     // eslint-disable-next-line no-var
  //     var points = [];
  //     let temp= blist[i].geometry.coordinates[0];
  //     for(let i = 0 ; i < temp[0].length ; i++){
  //       let tp = temp[0][i];
  //       points.push(tp);
  //     }
  //     // 将闭合区域加到遮蔽层上，每次添加完后要再加一次西北角作为下次添加的起点和最后一次的终点
  //     pArray = pArray.concat(points);
  //     pArray.push(pArray[0]);
  //   }
  //   const go = {
  //     "type": "Feature",
  //     "properties": {},
  //     "geometry": {
  //       "type": "Polygon",
  //       "coordinates": [pArray]
  //     }
  //   };
  //   map.addLayer({
  //     "id": "QueryBondsArea",
  //     "type": "fill",
  //     "source": {
  //       "type": "geojson",
  //       "data": go
  //     },
  //     "paint": {
  //       // 半透明深蓝色蒙版
  //       // "fill-color": "rgba(201, 201, 201,0.90)",
  //       "fill-outline-color": "rgba(172, 220, 243,0)",
  //
  //       // 不透明白色蒙版
  //       "fill-color": "rgba(30,84,111,0.9)",
  //       // "fill-outline-color": "#ffffff"**/
  //     }
  //   }," overlayer-tag");
  // },
  // // 清空高亮图层
  clearHLLayer(map) {
    if (this.HLLayer !== null) {
      this.activeMap.getSource('hl-source-map').setData({
        "type": "Feature",
        "geometry": {
          "type": "Polygon",
          "coordinates": [[]]
        }
      });
      if(this.activeMap.getSource('c-hl-source-map')){
        this.activeMap.removeLayer("c-hl-layer-map");
        this.activeMap.removeSource('c-hl-source-map');
      }
    }
    //清除区划标签
    regionLableLayer.cleanLables(map);
  },
  /**
   * 通过features直接刷新features
   * 刷新高亮图层的features,先清除后增加
   * layerType,type为fill时提供双击下钻，为line不提供双击下钻
   */
  refreshBoundaryFeatures(features, map,layerType) {
    //默认如果为空的话，不提供双击
    if(layerType === null || layerType === undefined || layerType === "undefined"){
      layerType = "line";
    }
    if (!features) {
      return;
    } // 初始化一下高亮图层
    this.initHLLayer(map,layerType);
    // 清除原有features
    this.clearHLLayer(map);

    // 添加feature图层
    this.activeMap.getSource('hl-source-map').setData(features);
    map.removeLayer("hl-layer-map");
    if(map.getLayer("hl-layer-map-line") !== undefined){
      map.removeLayer("hl-layer-map-line");
    }
    map.addLayer({
      "id": "hl-layer-map",
      "type": "fill",
      "source": "hl-source-map",
      "paint": {
        "fill-color": "rgba(0,203,246,0.3)",
        'fill-outline-color': "rgb(105, 151, 234)",
      }
    }," overlayer-tag");
    map.addLayer({
      "id": "hl-layer-map-line",
      "type": "line",
      "source": "hl-source-map",
      "paint": {
        // "line-color": "hsl(6,86%,36%)",
        "line-color": "rgb(105, 151, 234)",
        "line-width": 3,
        "line-opacity": 0.9
      },
    }," overlayer-tag");
    // 地图平滑缩放显示所有boundary
    map.fitBounds(this.getBoundsByFeatures(features), { padding: 200 });
    EventBus.$emit("refreshBoundaryFeaturesComplete"); // 报告区划边界平滑缩放完成
  },
  //处理所有features，返回范围bounds
  getBoundsByFeatures(features){
    let bounds = [[], []];
    for (let j = 0; j < features.features.length; j++) {
      let layerTemp = features.features[j];
      for (var i = 0; i < layerTemp.geometry.coordinates.length; i++) {
        let polygon;
        let latitude;
        let longitude;
        // if (layerTemp.geometry.coordinates.length === 1) {
        //   // Polygon coordinates[0][nodes]
        //   polygon = layerTemp.geometry.coordinates[0];
        // } else {
        //   // Polygon coordinates[poly][0][nodes]
        //   polygon = layerTemp.geometry.coordinates[i][0];
        // }
        polygon = layerTemp.geometry.coordinates[i][0];

        for (var q = 0; q < polygon.length; q++) {
          longitude = polygon[q][0];
          latitude = polygon[q][1];

          bounds[0][0] = bounds[0][0] < longitude ? bounds[0][0] : longitude;
          bounds[1][0] = bounds[1][0] > longitude ? bounds[1][0] : longitude;
          bounds[0][1] = bounds[0][1] < latitude ? bounds[0][1] : latitude;
          bounds[1][1] = bounds[1][1] > latitude ? bounds[1][1] : latitude;
        }
      }
    }
    return bounds;
  },
  // 如果区划跨面（特色区划可能会跨面）的话要分批去请求，暂时先这样写着
  addRegionLableByRegionInfos(regions,map){
    // 区划等级一致所以区划所在面一致
    let regionlevel = regions[0].regionlevel;
    let dataSetName = regions[0].rname;
    let currRcid = regions[0].rcid;
    let  regiontype = regions[0].regiontype;
    let sqlCondiftionArr = new Array();
    for (let i = 0; i < regions.length; i++) {
      sqlCondiftionArr.push(
        "QH_CODE = '" + regions[i].regioncode + "'"
      );
    }
    // 查询添加添加区划标签  空间查询
    let stPName = dataSetName.replace("ST_R", "ST_P");
    let sqlCondition = sqlCondiftionArr.join(" or ");
    sgisSpatialQuery.queryAttributeBySQL(
      stPName,
      sgisRegionBase.regionCatalog.getCurrDataSource(),
      sqlCondition,
      function(e) {
        let regioninfos = [];
        for (let j = 0; j < e.result.recordsets.length; j++) {
          let rfeatures = e.result.recordsets[j].features;
          for (let i = 0; i < rfeatures.features.length; i++) {
            let feature = rfeatures.features[i];
            let regioninfo = {
              id: feature.properties.QH_CODE,
              rcid: currRcid,
              regioncode: feature.properties.QH_CODE,
              regionname: feature.properties.QH_NAME,
              regiontype: regiontype,
              regionlevel: regionlevel,
              origincode: "",
              parcode: "",
              lat: feature.properties.SmY,
              lon: feature.properties.SmX,
              rname: dataSetName,
              pname: stPName
            };
            regioninfos.push(regioninfo);
          }
        }
        try {
          regionLable.createLayer(regioninfos, map);
        } catch (e) {
          console.log(e);
        }
      });
  }
};
